package bosc.cn.service.wallet.impl;

import bosc.cn.constant.OrderConstants;
import bosc.cn.dto.common.CommonResponse;
import bosc.cn.dto.common.ResponseWrapper;
import bosc.cn.service.wallet.WalletListService;
import bosc.cn.service.wallet.bo.WalletListReqBO;
import bosc.cn.service.wallet.bo.WalletListResBO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mapper.WalletInfoMapper;
import model.WalletInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WalletListServiceImpl implements WalletListService {

    @Autowired
    private WalletInfoMapper walletInfoMapper;

    @Override
    public ResponseWrapper<WalletListResBO> getWalletList(WalletListReqBO reqBO) {

        ResponseWrapper<WalletListResBO> resBO = new ResponseWrapper<>();
        CommonResponse head = new CommonResponse();
        WalletListResBO body = new WalletListResBO();

        try {

            // 正常通信
            head.setRetCd("000000");
            head.setRetMsg("通信成功");
            head.setRetTm(LocalDateTime.now());

            // 分页参数校验
            if (reqBO.getCurrentPage() == null || reqBO.getPageSize() == null ||
                    reqBO.getCurrentPage().isEmpty() || reqBO.getPageSize().isEmpty()) {
                body.setPrcSts("PR99");
                body.setPrcMsg("分页参数不能为空");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            // 校验分页参数
            int currentPage;
            int pageSize;
            try {
                currentPage = Integer.parseInt(reqBO.getCurrentPage());
                pageSize = Integer.parseInt(reqBO.getPageSize());
            } catch (NumberFormatException e) {
                body.setPrcSts("PR88");
                body.setPrcMsg("分页参数格式错误");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            if (pageSize <= 0) {
                body.setPrcSts("PR77");
                body.setPrcMsg("每页条数必须大于0");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            // 构建查询条件
            QueryWrapper<WalletInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cst_no", reqBO.getCstNo())
                    .eq("wlt_sts", "WS01"); // 只查正常状态的钱包

            // 判断排序方式
            if (OrderConstants.TIME_ASC.equals(reqBO.getOrderFlag())) {
                queryWrapper.orderByAsc("wlt_auth_dt");
            } else {
                queryWrapper.orderByDesc("wlt_auth_dt"); // 默认降序
            }

            // 查询总记录数
            long totalNo = walletInfoMapper.selectCount(queryWrapper);
            if (totalNo == 0) {
                body.setPrcSts("PR66");
                body.setPrcMsg("未查询到钱包信息");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            // 计算总页数
            long totalPage = (totalNo + pageSize - 1) / pageSize;

            // currentPage 校验
            if (currentPage < 1) {
                currentPage = 1;
            } else if (currentPage > totalPage) {
                currentPage = (int) totalPage;
            }

            // 分页查询
            Page<WalletInfo> page = new Page<>(currentPage, pageSize);
            IPage<WalletInfo> walletPage = walletInfoMapper.selectPage(page, queryWrapper);

            // 返回结果
            body.setPrcSts("PR00");
            body.setPrcMsg("钱包列表查询成功");
            body.setTotalNo(walletPage.getTotal());      // 总记录数
            body.setTotalPage(walletPage.getPages());    // 总页数
//            resBO.setCurrentPage(walletPage.getCurrent());     // 当前页
//            resBO.setPageSize(walletPage.getSize());      // 每页大小
            // 转换实体类 -> BO
            List<WalletListResBO.WalletInfoBO> boList = walletPage.getRecords().stream()
                    .map(info -> {
                        WalletListResBO.WalletInfoBO bo = new WalletListResBO.WalletInfoBO();
                        bo.setWltId(info.getWltId());
                        bo.setWltName(info.getWltName());
                        bo.setWltSts(info.getWltSts());
                        bo.setWltBal(info.getWltBal());
                        bo.setWltBalLmt(info.getWltBalLmt());
                        bo.setSngLmtAmt(info.getSngLmtAmt());
                        bo.setWltAuthDt(info.getWltAuthDt());
                        return bo;
                    })
                    .collect(Collectors.toList());

            body.setWltInfoList(boList);

        } catch (Exception e) {
            // 出现异常，通信失败
            head.setRetCd("999999");
            head.setRetMsg("系统异常：" + e.getMessage());
            head.setRetTm(LocalDateTime.now());

        }
        resBO.setHead(head);
        resBO.setBody(body);
        return resBO;

    }
}

